/*
 * @Description: ***
 * @Version: 1.0.0
 * @Autor: Caoyingwen
 * @Date: 2021-12-23 10:44:41
 * @LastEditors: Caoyingwen
 * @LastEditTime: 2021-12-23 15:50:14
 */

import {
  AjaxPlugin
} from 'vux'
console.log(process.env, '--env')
// AjaxPlugin.$http.defaults.baseURL = process.env.VUE_APP_BASE_SERVER_URL
AjaxPlugin.$http.defaults.baseURL = process.env.NODE_ENV === 'development' ? '' : process.env.VUE_APP_BASE_SERVER_URL // 本地开发不使用nginx代理时

// 添加请求拦截器
AjaxPlugin.$http.interceptors.request.use(function (config) {
  //  在发送请求之前做些什么
  let timestamp = +new Date()
  if (config.method === 'get') {
    config.transformRequest = [function (data) {
      let ret = []
      for (let it in data) {
        ret.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
      }
      config.url += '?' + ret.join('&')
      return ret.join('&')
    }]
  } else if (config.method === 'post') {
    config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    config.transformRequest = [function (data) {
      let ret = []
      for (let it in data) {
        ret.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]))
      }
      return ret.join('&')
    }]
  }
  config.timeout = 20000
  config.headers['timestamp'] = timestamp
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
AjaxPlugin.$http.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error)
})

export default AjaxPlugin